//
//  NSArray+Map.m
//  AmountBody
//
//  Created by Qiu Jishuai on 2017/12/30.
//  Copyright © 2017年 RCMTM. All rights reserved.
//

#import "NSArray+Map.h"

@implementation NSArray (Map)

- (NSArray *)map: (TransformBlock)transform filterNil: (BOOL)filterNil {
    NSUInteger capacity = self.count;
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:capacity];
    [self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL * stop) {
        id transformedObj = transform(obj);
        if (!transformedObj && !filterNil) {
            transformedObj = [NSNull null];
        }
        [array addObject:transformedObj];
    }];
    return [array copy];
}

- (NSArray *)map: (TransformBlock)transform {
    return [self map:transform filterNil:NO];
}

- (NSArray *)filter: (FilterBlock)transform {
    NSMutableArray *array = [NSMutableArray array];
    [self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL * stop) {
        if (transform(obj)) {
            [array addObject:obj];
        }
    }];
    return [array copy];
}
//- (NSArray *)flatMap: (TransformBlock)transform {
//    NSUInteger capacity = self.count;
//    NSMutableArray *array = [NSMutableArray arrayWithCapacity:capacity];
//
//    [self enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//        id transformedObj = transform(obj);
//        if (transformedObj) {
//            NSString *className = NSStringFromClass([obj class]);
//            if ([className isEqualToString:@"NSArray"] || [className isEqualToString:@"NSMutableArray"]) {
//                [array addObjectsFromArray:transformedObj];
//            } else {
//                [array addObject:transformedObj];
//            }
//        }
//    }];
//    return [array copy];
//}

@end
